﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace EffiProz.Core.Lib.IO
{
    public class CountdownInputStream : Stream
    {
        private long count;
        private Stream input;

        public CountdownInputStream(Stream ips)
        {
            this.input = ips;
        }

        public override int ReadByte()
        {

            if (this.count <= 0)
            {
                return -1;
            }

            int b = this.input.ReadByte();

            if (b >= 0)
            {
                this.count--;
            }

            return b;
        }


        public override int Read(byte[] buffer, int offset, int count)
        {

            if (this.count <= 0)
            {
                return -1;
            }

            if (count > this.count)
            {
                count = (int)this.count;
            }

            int r = this.input.Read(buffer, offset, count);

            if (r > 0)
            {
                this.count -= r;
            }

            return r;
        }

        public override void Close()
        {
            this.input.Close();
        }

        public long getCount()
        {
            return this.count;
        }

        public void setCount(long count)
        {
            this.count = count;
        }

        public override void Write(byte[] buffer, int offset, int count)
        {
            this.input.Write(buffer, offset, count);
        }

        public override void SetLength(long value)
        {
            this.input.SetLength(value);
        }

        public override long Seek(long offset, SeekOrigin origin)
        {
            return this.input.Seek(offset, origin);
        }


        public override void Flush() { }


        public override long Position
        {
            get
            {
                return this.input.Position;
            }

            set
            {
                this.input.Position = value;
            }
        }

        public override long Length
        {
            get
            {
                return count;
            }
        }

        public override bool CanRead
        {
            get
            {
                return this.input.CanRead;
            }
        }

        public override bool CanSeek
        {
            get
            {
                return this.input.CanSeek;
            }
        }

        public override bool CanWrite
        {
            get
            {
                return this.input.CanWrite;
            }
        }
    }
}
